package com.gitee.easyopen.bean;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.gitee.easyopen.ApiParam;
import com.gitee.easyopen.exception.DuplicateApiNameException;

/**
 * 负责存储定义好的接口信息
 * 
 * @author tanghc
 *
 */
public class DefinitionHolder {
    // key:nameversion
    private static Map<String, ApiDefinition> apiDefinitionMap = new ConcurrentHashMap<String, ApiDefinition>(64);

    public static void addApiDefinition(ApiDefinition apiDefinition) throws DuplicateApiNameException {
        String key = getKey(apiDefinition);
        boolean hasApi = apiDefinitionMap.containsKey(key);
        if (hasApi) {
            throw new DuplicateApiNameException("重复申明接口,name:" + apiDefinition.getName() + " ,version:"
                    + apiDefinition.getVersion() + ",method:" + apiDefinition.getMethod().getName());

        }
        apiDefinitionMap.put(key, apiDefinition);
    }

    /**
     * 获取全部接口
     * @return
     */
    public static List<Api> listAllApi() {
        Collection<ApiDefinition> allApi = apiDefinitionMap.values();
        List<Api> ret = new ArrayList<>(allApi.size());
        for (ApiDefinition apiDefinition : allApi) {
            ret.add(new Api(apiDefinition.getName(),apiDefinition.getVersion()));
        }
        return ret;
    }
    
    public static Map<String, ApiDefinition> getApiDefinitionMap() {
        return apiDefinitionMap;
    }

    public static ApiDefinition getByParam(ApiParam param) {
        String key = getKey(param.fatchName(), param.fatchVersion());
        return apiDefinitionMap.get(key);
    }

    public static String getKey(ApiDefinition apiDefinition) {
        return getKey(apiDefinition.getName(), apiDefinition.getVersion());
    }

    public static String getKey(String name, String version) {
        return name + version;
    }

}
